// JavaScript Document
function getAjax(url, params, eID, method, dataType, showLoading, onSuccess, onError, onComplete)
{
	showLoading = (typeof(showLoading) === 'undefined' || showLoading === '') ? true : showLoading;
	method = (typeof(method) == 'undefined' || method == '' || (method.toUpperCase() != 'POST' && method.toUpperCase() != 'GET') ) ? 'GET' : method.toUpperCase();
	dataType = (typeof(dataType) == 'undefined' || dataType == '') ? 'html' : dataType;
	
	if(typeof(onSuccess) == 'undefined' || onSuccess == '')
	{
		var _onSucess = function(data)
		{
			if(dataType.toLocaleLowerCase() == 'json')
			{
				$(eID).html(data.form);
			}
			else
			{
				$(eID).html(data);
			}
		};
	}
	else
	{
		var _onSucess = onSuccess;
	}
	
	if(typeof(onError) == 'undefined' || onError == '')
	{
		var _onError = function(jqXHR, textStatus, errorThrown){
			try {
				$(eID).html("Sorry. There was an error.");
			}
			catch (e) {
				alert("Sorry. There was an error.");
			}
		};
	}
	else
	{
		var _onError = onError;
	}
	
	if(typeof(onComplete) == 'undefined' || onComplete == '')
	{
		var _onComplete = function(jqXHR, textStatus){
		};
	}
	else
	{
		var _onComplete = onComplete;
	}
	
	if(showLoading)
	{
		//var h=parseInt($('#'+eID).offset().top);
		//h=(h==0)?'auto':(h+"px");
		$(eID).html('<span class="ajaxLoading">&nbsp;</span>');
	}
	$.ajax({
		   		type: method,
				url: url,
				dataType: dataType,
				data: params,
				success: _onSucess,
				error: _onError,
				complete: _onComplete
			 });
}


function getQueryParam(paramName) {
	strQuery = window.location.search.substring(1);
	arrParam = strQuery.split("&");
	for (i=0;i<arrParam.length;i++)
	{
		var paramItem = arrParam[i].split("=");
		if (paramItem[0] == paramName)
		{
			return paramItem[1];
		}
	}
	return '';
}

function isIntNumber(sText)
{
   var ValidChars = "0123456789";
   var IsNumber=true;
   var Char;
   for (i = 0; i < sText.length; i++) 
   { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1 || sText.charAt(0) == "0")
      {
         IsNumber = false;
         break;
      }
   }
   return IsNumber;
}

function strIsNumber(sText)
{
	var ValidChars = "0123456789";
	var IsNumber=true;
	var Char;
	for (i = 0; i < sText.length; i++) 
	{ 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1)
		{
			IsNumber = false;
			break;
		}
	}
	return IsNumber;
}

// arrAllowType:  array('.jpg', '.gif', '.png')
function uploadValidExtension(fileName, arrAllowType)
{
    if(fileName == "")
    {
        return false;
    }
    fileName = fileName.toLowerCase();
    var extension     = fileName.substr(fileName.lastIndexOf('.'), fileName.length);
    var check = false;
    for(var i in arrAllowType)
    {
        if(arrAllowType[i] == extension)
        {
            check = true;
            break;
        }
    }    
    return check;
}// JavaScript Document

function isUrl(s) {
	//var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
	//return regexp.test(s);
	var RegexUrl = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
 	var RegExp = /^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/;
    if(RegExp.test(s) && RegexUrl.test(s)){
        return true;
    }else{
        return false;
    }
}


var UrlEncode = {
 
	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},
 
	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
		return string;
	}
};

function stripHtmlTags(str)
{
	return str.replace(/<\/?[^>]+>/gi, '');
}

function getSelText()
{
    var txt = '';
    if (window.getSelection)
    {
        txt = window.getSelection();
	}
    else if (document.getSelection)
    {
        txt = document.getSelection();
    }
    else if (document.selection)
    {
        txt = document.selection.createRange().text;
    }
	return txt;
}

function getDomainFromUrl(strUrl)
{
	if(strUrl == '') return '';
	return strUrl.match(/:\/\/(.[^/]+)/)[1];
}

function validateUsername(uname) {
    var error = "";
    var illegalChars = /\W/; // allow letters, numbers, and underscores
 
    if (uname == "") {
        error = "Bạn hãy nhập Tên đăng nhập.";
    } else if ((uname.length < 4) || (uname.length > 64)) { 
        error = "Tên đăng nhập của bạn quá ngắn, độ dài phải từ 4-64 ký tự!";
    } else if (illegalChars.test(uname)) { 
        error = "Tên đăng nhập có chứa ký tự không hợp lệ.";
    }
    return error;
}

function validatePassword(pws) {
    var error = "";
    var illegalChars = /[\W_]/; // allow only letters and numbers 
 
    if (pws == "") {
        error = "Bạn chưa nhập Mật khẩu.";
    } else if ((pws.length < 6) || (pws.length > 64)) {
        error = "Mật khẩu của bạn quá ngắn, độ dài mật khẩu từ 6-64 ký tự!";
    } else if (illegalChars.test(pws)) {
        error = "Mật khẩu có chứa ký tự không hợp lệ.";
    }// else if (!((pws.search(/(a-z)+/)) && (pws.search(/(0-9)+/)))) {
       // error = "The password must contain at least one numeral.";
    //}
   return error;
}

function validateEmail(email) {
    var error="";
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
   
    if (email == "") {
        error = "Bạn chưa nhập địa chỉ Email.";
    } else if (!emailFilter.test(email)) {              //test email for illegal characters
        error = "Địa chỉ Email không hợp lệ.";
    } else if (email.match(illegalChars)) {
        error = "Địa chỉ Email chứa ký tự không hợp lệ.";
    }
    return error;
}

// number format
function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1))
	{
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}
function roundNumber(num, dec) {
	return Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
}
// end number format
var ajaxLoadingPopupStatus = 0;
function loadAjaxLoadingPopup(imgId, divBgId){
	//loads popup only if it is disabled
	if(ajaxLoadingPopupStatus==0){
		centerAjaxLoadingPopup(imgId, divBgId);
		$(divBgId).css({
			"opacity": "0.5"
		});
		$(divBgId).fadeIn("fast");
		$(imgId).fadeIn("fast");
		ajaxLoadingPopupStatus = 1;
		
	}
}
function centerAjaxLoadingPopup(imgId, divBgId){
	//request data for centering
	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;
	var bodywidth = $('body').innerWidth();
	var bodyheight = $('body').innerHeight();
	var popupHeight = $(imgId).height();
	var popupWidth = $(imgId).width();
	
	var wpos = (bodywidth > windowWidth) ? bodywidth : windowWidth;
	var hpos = (bodyheight > windowHeight) ? bodyheight : windowHeight;
	var scrollWindow = $(window).scrollTop();
	var top = windowHeight/2-((popupHeight/3)*2) + scrollWindow;
	var left = windowWidth/2-popupWidth/2;
	
	//centering
	$(imgId).css({
		"position": "absolute",
		"top": top,
		"left": left
	});
	//only need force for IE6
	$(divBgId).css({
		"height": hpos,
		"width" : wpos
	});

	$(window).scroll(function(){		
		if($(imgId).css('display') != 'none')
		{
			$(imgId).stop();
			var scroll = $(window).scrollTop();
			var scrollPos = windowHeight/2-((popupHeight/3)*2) + scroll;
			$(imgId).animate({top: scrollPos},'slow');
		}
	});
}
function disableAjaxLoadingPopup(imgId, divBgId){
	//disables popup only if it is enabled
	if(ajaxLoadingPopupStatus==1){
		$(divBgId).fadeOut();
		$(divBgId).hide();
		
		ajaxLoadingPopupStatus = 0;
	}
	$(imgId).hide();
}